package com.ztjava.plugin.event;

import java.io.IOException;
import java.net.ServerSocket;
import java.rmi.AccessException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import com.ztjava.plugin.event.service.EventService;
import com.ztjava.plugin.event.service.EventServiceImpl;

/**
 * Rmi服务端配置
 * @author lcm
 *
 */
public class RmiServerConfig {
	public String getHost() {
		return host;
	}
	public void setHost(String host) {
		this.host = host;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	private String host;
	private String name;
	private Registry registry;
	public int getPort() {
		return port;
	}

	private int port;
	public Registry getRegistry() {
		return registry;
	}
	public void setRegistry(Registry registry) {
		this.registry = registry;
	}

	public RmiServerConfig(String host,String name) {
		this.name = name;
		this.host = host;
	}
	
	public boolean start() {
		//同一服务器不同应用，请绑定不同端口
		try {
			port = getGoodPort();
			registry = LocateRegistry.createRegistry(port);	
			EventService eventService = new EventServiceImpl();
			String rmi = "rmi://"+host+":"+port+"/"+name;
			System.out.println(rmi);
			Naming.rebind(rmi, eventService);
			EventKit.setServerRim(rmi);
			return true;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static int getGoodPort(){
		for(int i = 8936; i<8999; i++){
			try {
				ServerSocket sskt = new ServerSocket(i);
				System.out.println("找到可用端口："+i);
				sskt.close();
				return i;
			} catch (IOException e) {
				System.out.println("寻找下个可用端口："+i);
			}
		}
		return 8935;
	}
	
	public boolean stop() {
		try {
			String[] services = registry.list();
			for (String service : services) {
				Remote remote = registry.lookup(service);
				UnicastRemoteObject.unexportObject(remote, true);
				registry.unbind(service);
			}
			return true;
		} catch (AccessException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}
		return false;
	}
}
